var redis = require('../db/redis')
var pu = require('../tool/public')
var mg = require('../db/userdb')
var wx = require('../tool/wxResult')
var md5 = require('md5')

/**
 * @Description: 用户信息类
 * @author longfa liang
 * @date 2021/7/14
 */

class users {
    /*微信绑定手机号*/
    async wechat_bind_phone (req, res, next) {
        var phone = req.body.phone
        var openid = req.body.openid
        let isnull = pu.isnull([phone, openid])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        /*微信绑定手机号
        * 1、验证手机号是否注册
        * 2、微信id绑定到手机号 删除微信用户信息
        * */
        let userinfo = await mg.findOne('users', { phone: Number(phone) })
        let wechat_userinfo = await mg.findOne('users', { openid: openid })
 
        if (userinfo) { //有用户信息 把微信内容绑定到手机
            if(userinfo._id.toString()=== wechat_userinfo._id.toString()){
                pu.success('成功', { userid: wechat_userinfo._id, openid: wechat_userinfo.openid }, res)
                return
            }
            mg.updateOne('users', { _id: userinfo._id }, { $set: { openid:wechat_userinfo.openid, avatarUrl: wechat_userinfo.avatarUrl,wechat_session_key:wechat_userinfo.wechat_session_key} })
            mg.deleteOne('users',{_id:wechat_userinfo._id})
            var token =  await redis.get("USER_TOKEN_"+ userinfo._id.toString())
            if(!token){
             token = pu.uuid()
             await redis.set("USER_TOKEN_"+ userinfo._id.toString(),token)
            }
            pu.success('成功', { userid: userinfo._id, openid: userinfo.openid,token: token }, res)
        } else { //没有用户信息直接吧手机号绑定到用户
            wechat_userinfo.phone = phone
            // console.log(wechat_userinfo);
            mg.updateOne('users', { _id: wechat_userinfo._id }, { $set: {  phone: Number(phone) } })
            pu.success('成功', { userid: wechat_userinfo._id, openid: wechat_userinfo.openid }, res)
        }
    }

    /*小程序登录*/
    async wechat_login (req, res, next) {
        var openid = req.body.openid
        var avatarUrl = req.body.avatarUrl
        var wechat_session_key = req.body.wechat_session_key
        var city = req.body.city
        var country = req.body.country
        var gender = req.body.gender
        var province = req.body.province

        let isnull = pu.isnull([openid, wechat_session_key])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        let userinfo = await mg.findOne('users', { openid: openid })

        if (!userinfo) { //没有账号 注册

            let token = pu.uuid()
            let usersql = {
                'openid': openid, //微信openID
                'avatarUrl': avatarUrl, //头像地址
                'wechat_session_key': wechat_session_key, //微信session
                'city': city,//所在城市
                'qq': '',//QQ
                'country': country,//所在国家
                'gender': gender,  //1男2女 0 未知
                'name': '',//名字
                'phone': 0,//手机号
                'province': province,//省份
                'birthday': '',//生日
                'email': '',//生日
                'password': '',
                'is_delete': 0,//是否禁用
                'deleteMsg': '',//禁用原因
                'group_list': [],//组织id
                'last_group_id': '',//当前所在组织id
                'last_group_name': '',//当前所在组织名字
                'token':token,
            }
            let insertinfo = await mg.insertOne('users', usersql)
            usersql.loginstatus = 1
            usersql.template = []
            let userid = insertinfo.insertedId
            await redis.set('USER_TOKEN_' + userid, token,86400000)
            usersql.userid = userid
            pu.success('成功', usersql, res)

        } else {
            this.login(userinfo, 1, res)
        }

    }

    async getUserOpenId (req, res, next) {
        let code = req.body.code
        if (!code) {
            pu.fail('code不能空', res)
            return
        }
        let data = await wx.getOpenId(code)
        if (data) { //获取到数据
            pu.success('获取成功', data, res)
        } else {
            console.error(code, 'wx login fail', JSON.stringify(data))
            pu.fail('获取openId失败', res)
        }
    }

    /*修改*/
    async update_userinfo (req, res, next) {
        var userid = req.headers.userid
        let info = req.body.info
        var where = {}
        for (var obj in info) {
            if (obj == 'last_group_id') {
                where[obj] = mg.ObjectID(info[obj])
            } else {
                where[obj] = info[obj]
            }
        }
        let isnull = pu.isnull([userid, info])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        await  mg.updateOne('users', { _id: mg.ObjectID(userid) }, { $set: where })
        pu.success('成功', info, res)
    }

    /*获取用户信息*/
    async get_userinfo (req, res, next) {
        var userid = req.headers.userid
        let userinfo = await mg.findOne('users', { _id: mg.ObjectID(userid) })
        if (userinfo) {
            var info = {
                last_group_id: userinfo.last_group_id,
                last_group_name: userinfo.last_group_name,
                group_list: userinfo.group_list, //拥有的所有组织
                userid: userinfo._id,
                name: userinfo.name,
                phone: userinfo.phone.toString().slice(0, 3) + '****' + userinfo.phone.toString().slice(7, 11),
                openid: userinfo.openid,//微信openID
                avatarUrl: userinfo.avatarUrl,//头像地址
                city: userinfo.city,//所在城市
                qq: userinfo.qq,//qq
                country: userinfo.country,//所在国家
                email: userinfo.email,//所在国家
                gender: userinfo.gender,//1男2女 0 未知
            }
            this.login(userinfo, 1, res, true)
        } else {
            pu.fail('ID不正确', res)
            return
        }
    }


    /*短信登录*/
    async smscode_login (req, res, next) {
        let phone = req.body.phone
        let phone_code = req.body.phone_code
        let isnull = pu.isnull([phone, phone_code])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }

        /*插入信息*/
        let usersql = {
            'openid': req.body.openid, //微信openID
            'avatarUrl': req.body.avatarUrl, //头像地址
            'wechat_session_key': req.body.wechat_session_key, //微信session
            'city': '',//所在城市
            'qq': '',//QQ
            'country': '',//所在国家
            'gender': 0,  //1男2女 0 未知
            'name': '',//名字
            'phone': 0,//手机号
            'province': '',//省份
            'birthday': '',//生日
            'password': '',
            'is_delete': 0,//是否禁用
            'deleteMsg': '',//禁用原因
            'email': '',//邮箱
            'group_list': [],//组织id
            'last_group_id': '',//当前所在组织id
            'last_group_name': '',//当前所在组织名字

        }


        let smscode = await redis.get('SMS_CODE_' + phone)
        
        if (smscode != phone_code) {
            pu.fail('验证码不正确', res)
            return
        }
        let userinfo = await mg.findOne('users', { phone: Number(phone) })
        if (!userinfo) { //没有用户信息 直接注册

            /*注册需要查询组织中是否有该号码*/
            let team_user_info = await mg.find('team_users', { phone: Number(phone) })
            var name = ''
            var userinfo_team = {
                group_list: [],
                last_group_id: '',
                last_group_name: '',
            }
            var team_users_where = {}

            if (team_user_info.length) { //被邀请过
                name = team_user_info[0].name
                team_users_where['$or'] = []
                /*同步组织用户表*/
                for (var i = 0; i < team_user_info.length; i++) {

                    let teaminfo = await mg.findOne('team', { _id: team_user_info[i].team_id })
                    userinfo_team.group_list.push(teaminfo._id)
                    userinfo_team.last_group_id = teaminfo._id
                    userinfo_team.last_group_name = teaminfo.name
                    team_users_where['$or'].push({ _id: team_user_info[i]._id })
                    userinfo_team.last_group_name = team_user_info[i].name
                }
                console.log('注册已经存在组织信息', JSON.stringify(userinfo_team))
            }
            /*同步用户表*/
            let token = pu.uuid()
            var resinfo = {
                name: name,
                phone: phone.slice(0, 3) + '****' + phone.slice(7, 11),
                token: token,
                meal_name: '',
                meal_price: '',
                last_group_id: userinfo_team.last_group_id,
                last_group_name: userinfo_team.last_group_name,
                group_list: userinfo_team.group_list, //拥有的所有组织
                openid: '',//微信openID
                avatarUrl: '',//头像地址
                city: '',//所在城市
                qq: '',//qq
                country: '',//所在国家
                gender: 0,//1男2女 0 未知
                'loginstatus': 1,
                template: [],
            }

            for (var obj in resinfo) {
                if (obj == 'loginstatus' || obj == 'phone') {
                    continue
                } else {
                    usersql[obj] = resinfo[obj]
                }
            }
            usersql.phone = Number(phone)
            let insertinfo = await mg.insertOne('users', usersql)
            let userid = insertinfo.insertedId

            if (team_user_info.length) {
                mg.update('team_users', team_users_where, { $set: { userid: userid } })
            }
            await redis.set('USER_TOKEN_' + userid, token, 86400000)
            resinfo.userid = userid
            pu.success('成功', resinfo, res)
            return


        } else {
            this.login(userinfo, 1, res)
        }

    }


    async pwd_login (req, res, next) {
        let password = req.body.password
        let phone = req.body.phone
        let code = req.body.code
        let uuid = req.body.uuid
        let isnull = pu.isnull([password, phone, code, uuid])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }

        let imgcode = await redis.get('IMG_CODE_' + uuid)
        if (!imgcode) {
            pu.fail('验证码过期', res)
            return
        }
        if (code != imgcode.toUpperCase()) {
            pu.fail('验证码不正确', res)
            return
        }

        password = pu.decode64(password)
        let userinfo = await mg.findOne('users', { phone: Number(phone) })
        if (!userinfo) {
            pu.fail('账号不正确', res)
            return
        }
        if (userinfo.password !== md5('cs_' + password)) {
            pu.fail('密码不正确', res)
            return
        }
        this.login(userinfo, 0, res)

    }

    /**
     * 统一登录成功后返回信息
     * @returns {Promise<void>}
     * tokenstatus 是否存token
     *
     */
    async login (userinfo, status, res, tokenstatus) {
        if (userinfo.is_delete) {
            pu.success('账户被禁用', resinfo, res)
            return
        }

        /**
         * 1、查询用户全部角色
         * 2、查询拥有权限
         * 3、拼接模板
         */
        var template = []
        var temp = []
        if (userinfo.last_group_id) {
            var jurlist = []
            let teamuserinfo = await mg.findOne('team_users', { userid: userinfo._id })
            var team_id = userinfo.last_group_id
            var team_userid = teamuserinfo._id
            let role = await redis.get('USER_ROLE_' + team_id.toString())
            if (role) {
                role = role.split(',')
                //获取角色中全部权限id
                for (var i = 0; i < role.length; i++) {
                    let jurid = await redis.hget('JURINFO_ROLE_' + team_id.toString(), role[i])
                    if (jurid) {
                        jurid = jurid.split(',')
                        jurlist = jurlist.concat(jurid)
                    }
                }
            }
            console.log('全部权限', jurlist)
            //获取单个权限id
            let juid = await redis.hget('JURINFO_USER_' + team_id, team_userid.toString())
            if (juid) {
                jurlist.push(juid)
            }
            console.log('JURINFO_USER_' + team_id, team_userid.toString())
            for (var i = 0; i < jurlist.length; i++) {
                let info = await redis.hget('JURINFO_' + team_id, jurlist[i])
                if (!info) {
                    continue
                }
                info = JSON.parse(info)
                for (var j = 0; j < info.length; j++) {
                    let obj = info[j]
                    if (!obj) {
                        console.log(obj)
                        break
                    }
                    if (obj.status == 1) {//拥有模块权限
                        var model = {}
                        model.name = obj.name
                        model.url = obj.url
                        model.module = obj.module
                        model.jur = []
                        for (var k = 0; k < obj.jur.length; k++) {
                            var list = {}
                            if (obj.jur[k].status == 1) {
                                list.name = obj.jur[k].name
                                list.server = obj.jur[k].server
                                list.url = obj.jur[k].url
                                list._id = obj.jur[k]._id
                                list.type = obj.jur[k].type

                                //jur去重复
                                var jur_flag = true;
                                for (var ij in model.jur){
                                    if(obj.jur[k].url == model.jur[ij].url){
                                        jur_flag = false;
                                        break;
                                    }
                                }
                                if(jur_flag){
                                    model.jur.push(list)
                                }
                            }
                        }
                        //module去重复
                        var flag = true;
                        for (var te in temp){
                            if(temp[te].module == model.module){
                                flag = false;
                                break;
                            }
                        }
                        if(flag){
                            temp.push(model)
                        }
                    }
                }
            }
            template = temp
        }
        let token = pu.uuid()
        let userid = userinfo._id
        var resinfo = {
            userid: userinfo._id.toString(),
            name: userinfo.name,
            phone: userinfo.phone  === 0 ? 0 :userinfo.phone.toString().slice(0, 3) + '****' + userinfo.phone.toString().slice(7, 11),
            token: token,
            meal_name: userinfo.meal_name,
            meal_price: userinfo.meal_price,
            group_list: userinfo.group_list,
            use_stop_time: userinfo.use_stop_time,
            auth_sum: userinfo.auth_sum,
            use_auth_sum: userinfo.use_auth_sum,
            last_group_id: userinfo.last_group_id,
            last_group_name: userinfo.last_group_name,
            openid: userinfo.openid,//微信openID
            avatarUrl: userinfo.avatarUrl,//头像地址
            city: userinfo.city,//所在城市
            qq: userinfo.qq,//qq
            country: userinfo.country,//所在国家
            gender: userinfo.gender,//1男2女 0 未知
            'loginstatus': 0,
            template: template
        }
        if (tokenstatus) {
            delete resinfo.token
        } else {
            await redis.set('USER_TOKEN_' + userid, token, 86400000)
        }
        pu.success('成功', resinfo, res)


    }


    /*设置密码*/
    async settingpwd (req, res, next) {
        let password = req.body.password

        let isnull = pu.isnull([password])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }
        password = pu.decode64(password)
        if (password.length > 20 || password.length < 6) {
            pu.fail('密码长度在6-20位之间', res)
            return
        }
        if (!pu.checkpwd(password)) {
            pu.fail('密码必须包含数字和字母', res)
            return
        }
        await mg.updateOne('users', { _id: mg.ObjectID(req.headers.userid) }, { $set: { password: md5('cs_' + password) } })
        pu.success('成功', '', res)
    }

    /*找回密码*/
    async find_pwd (req, res, next) {
        let phone = req.body.phone
        let phone_code = req.body.phone_code
        let password = req.body.password

        let isnull = pu.isnull([phone_code, phone])
        if (isnull) {
            pu.fail('参数不正确', res)
            return
        }

        password = pu.decode64(password)
        if (password.length > 20 || password.length < 6) {
            pu.fail('密码长度在6-20位之间', res)
            return
        }
        if (!pu.checkpwd(password)) {
            pu.fail('密码必须包含数字和字母', res)
            return
        }
        let smscode = await redis.get('SMS_CODE_' + phone)
        if (smscode != phone_code) {
            pu.fail('验证码不正确', res)
            return
        }
        let userinfo = await mg.findOne('users', { phone: Number(phone) })
        if (!userinfo) {
            pu.fail('账号未注册', res)
            return
        } else {
            await mg.updateOne('users', { _id: mg.ObjectID(req.headers.userid) }, { $set: { password: md5('cs_' + password) } })
            this.login(userinfo, 1, res)
        }
    }
}


module
    .exports = new users()
